/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.ufba.lasid.comm;

import br.ufba.lasid.base.Resource;
import br.ufba.lasid.base.ResourceList;
import br.ufba.lasid.base.Resourcetable;
import br.ufba.lasid.base.api.IResource;
import br.ufba.lasid.base.api.IResourcetable;
import br.ufba.lasid.comm.api.IHost;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

/**
 *
 * @author aliriosa
 */
public class Host extends Resource implements IHost{
    
    private Resourcetable rtable = new Resourcetable();
    private boolean       localhost = false;
    

    public Host(String hostID){
        super(hostID);
    }
    
    public Host(IResource parent, String hostID) {
        super(parent, hostID);
    }
        
    @Override
    public IResourcetable getResourcetable() throws Exception {
        return this.rtable;
    }

    @Override
    public void addResource(IResource resource) throws Exception {
        this.rtable.add(resource);
    }


    @Override
    public Kinds getKind() {
        return Kinds.Host;
    }

    @Override
    public void setKind(Kinds newKind) throws Exception {
        /**
         * We can not define a new kind to a host.
         */
    }    

    @Override
    public String getAddress() throws Exception {
        return this.getID();
    }
    
    
    @Override
    public void updateState() throws Exception {
        if(isLocalhost()){
            ResourceList resources = new ResourceList();
            resources.addAll(rtable.values());
            for(IResource resource : resources){
                resource.updateState();
            }
        }
    }
    
    @Override
    public boolean isLocalhost() throws Exception{
        return this.localhost;
    }
    
    @Override
    public void setLocalhost(boolean local) throws Exception{
        this.localhost = local;
    }
    
    public static boolean isLocalAddress(String hostAddress) throws Exception{
        
        Enumeration<NetworkInterface> nics = NetworkInterface.getNetworkInterfaces();
        
        while(nics.hasMoreElements()){
            NetworkInterface nic = nics.nextElement();
            Enumeration<InetAddress> addresses = nic.getInetAddresses();
            
            while(addresses.hasMoreElements()){
                InetAddress address = addresses.nextElement();
                
                if(address.getHostAddress().equalsIgnoreCase(hostAddress)){
                    return true;
                }
            }
        }
        
        return false;
        
    }
    
}
